
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ChatController;

import ChatSystem.ChatSystem;
import Model.User;
import Model.Users;
import chatGUI.ChatWindow;
import chatGUI.ConnectWindowPanel;
import chatNI.TCPCom;
import chatNI.TCPRec;
import chatNI.UDPRec;
import common.Bye;
import common.Fichier;
import common.Hello;
import common.Text;
import common.TransfertFileAccept;
import common.TransfertFileRequest;
import java.io.ByteArrayInputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Iterator;
import java.util.Set;

/**
 *
 * @author doutre
 */
public class ChatController extends Thread {

    private UDPRec rec;
    private Users userList;
    private User localUser = null;
    private ChatSystem cs;
    private Boolean running;

    /**
     *
     * @param cs
     * @throws SocketException
     */
    public ChatController(ChatSystem cs) throws SocketException {

        super();
        this.cs = cs;
        this.rec = new UDPRec(6666, this);
        this.userList = new Users();


    }

    /**
     *
     * @param rec
     */
    public void setRec(UDPRec rec) {
        this.rec = rec;
    }

    public void setRunning(Boolean running) {
        this.running = running;
    }

    public Boolean getRunning() {
        return running;
    }

    public void setLocalUser(User localUser) {
        this.localUser = localUser;
    }

    public User getLocalUser() {
        return this.localUser;
    }

    public void receive(byte[] classe) {

        ByteArrayInputStream ba = new ByteArrayInputStream(classe);
        ObjectInput in = null;

        try {
            in = new ObjectInputStream(ba);
            Object mess = in.readObject();


            if (mess instanceof Hello) {
                Hello mess2 = (Hello) mess;


                User u = new User(mess2.getUsername(), mess2.getAddr());
                userList.ajout(u);
                if (mess2.getReply() == true) {
                    System.out.println("Adresse :" + mess2.getAddr());
                    System.out.println("Nom :" + mess2.getUsername() + " vient de se connecter");
                    cs.getCwp().getChatArea().append(mess2.getUsername() + " vient de se connecter\n");
                    while (localUser == null) {
                    }
                    chatNI.ChatNI.sendHello(localUser.toString(), false);
                }

            } else if (mess instanceof Bye) {
                Bye mess2 = (Bye) mess;

                System.out.println(mess2.getAddr().toString() + " s'est déconnecté");

                String username = userList.getUserList().get(mess2.getAddr()).toString();
                cs.getCwp().getChatArea().append(username + " vient de se déconnecter\n");
                userList.suppr(mess2.getAddr());
            } else if (mess instanceof TransfertFileRequest) {

                TransfertFileRequest mess2 = (TransfertFileRequest) mess;
                System.out.println(mess2.getAddr() + " veut vous envoyer : " + mess2.getNomFichier());
                Boolean accepte = cs.getCwp().dialog(userList.getUserList().get(mess2.getAddr()).toString(), mess2.getNomFichier());
               
                
               if (accepte == true) {
                    chatNI.ChatNI.sendTransfertFileacc(true, mess2.getAddr());
                    TCPRec recep = new TCPRec(5555, mess2.getAddr(), mess2.getNomFichier());

                } else {
                    chatNI.ChatNI.sendTransfertFileacc(false, mess2.getAddr());

                }

            } else if (mess instanceof TransfertFileAccept) {
                TransfertFileAccept mess2 = (TransfertFileAccept) mess;
                if (mess2.getAccept() == true) {
                    System.out.println("Demande d'envoi acceptée");
                } else if (mess2.getAccept() == false) {
                    System.out.println("Demande d'envoi refusée");
                }

            } else if (mess instanceof Text) {
                Text mess2 = (Text) mess;

                if (userList.getWindows().get(mess2.getAddr()) != null) {
                    userList.getWindows().get(mess2.getAddr()).getUserChatArea().append(userList.getUserList().get(mess2.getAddr()).toString() + " says :" + "\n" + mess2.getContent() + "\n");
                } else {
                    String username = userList.getUserList().get(mess2.getAddr()).toString();
                    cs.getCwp().getChatArea().append(username + " démarre une conversation avec vous.\n");
                    ChatWindow w = userList.nouv_conv((User) userList.getUserList().get(mess2.getAddr()), this);
                    w.getUserChatArea().append((userList.getUserList().get(mess2.getAddr())).toString() + " says :\n" + mess2.getContent() + "\n");
                }

            } else if (mess instanceof Fichier) {
                Fichier mess2 = (Fichier) mess;

                // TODO : Enregistrer le fichier dans l'ordi
            }

        } catch (java.io.IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    public Users getUserList() {
        return userList;
    }

    public User getIndex(int num) {
        Set cles = userList.getUserList().keySet();
        Iterator it = cles.iterator();
        int count = 0;
        Object cle = null;
        while (count <= num) {
            count++;
            cle = it.next();
        }
        InetAddress cle2 = (InetAddress) cle;
        Object pers = userList.getUserList().get(cle2);
        User pers2 = (User) pers;
        return pers2;
    }

    public void del_conv(InetAddress a) {
        userList.getWindows().remove(a);
    }

    
    public void demarre() {
        try {
            this.running = true;
            if (this.rec == null) {
                this.rec = new UDPRec(6666, this);
            }
            this.rec.start();
            System.out.println("après start du cc");
        } catch (Exception e) {
            System.err.println(e);
        }
    }

    public void close_sock() {
        rec.getDatagrameSocket().close();
    }
}
